package com.acheli.registry.network.packet;

import com.acheli.ACHeli;
import com.acheli.registry.config.CustomDataBus;
import com.acheli.registry.network.ACHMessages;
import com.acheli.rideable.entites.RideableEntity;
import com.acheli.rideable.entites.ComponentEntity;
import com.acheli.rideable.functionLathes.ComponentFL;
import com.acheli.rideable.functionLathes.component.DefaultComponentProvider;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.NetworkDirection;
import net.minecraftforge.network.NetworkEvent;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.simple.SimpleChannel;

import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Supplier;

import static com.acheli.registry.entity.ACHEntities.RIDEABLE_COMPONENT_ENTITY_TYPE;

public class ComponentSpawnC2SPacket {
    // 添加字符串字段
    private final CompoundTag tag;

    // 从字节缓冲区解码
    public ComponentSpawnC2SPacket(FriendlyByteBuf buf) {
        this.tag = buf.readNbt();
    }

    public ComponentSpawnC2SPacket(UUID rideableUUID, String id) {
        tag = new CompoundTag();
        tag.putString("ID", id);
        tag.putUUID("rideableUUID", rideableUUID);
    }

    // 编码到字节缓冲区
    public void toBytes(FriendlyByteBuf buf) {
        buf.writeNbt(tag);
    }

    private boolean handle(Supplier<NetworkEvent.Context> supplier) {
        String ID = tag.getString("ID");
        UUID rideableUUID = tag.getUUID("rideableUUID");
        ACHeli.LOGGER.info("ComponentSpawnC2SPacket => ID: " + ID);
        NetworkEvent.Context context = supplier.get();
        context.enqueueWork(() -> {
            ServerPlayer player = context.getSender();
            if (player != null) {
                ServerLevel level = player.serverLevel();
                if  (level.getEntity(rideableUUID) instanceof RideableEntity rideable) {
                    // 原有生成实体的逻辑
                    ComponentFL fl = rideable.factory
                            .getProductFunction()
                            .getFL()
                            .getComponentFLByID(ID); //尝试静态注册

                    if (fl == null) { // 是动态注册
                        //从gson配置库扫描
                        List<DefaultComponentProvider> providerList =
                                CustomDataBus.gsonDefaultComponentProvidersMap.get(rideable.getFactoryName());
                        for (DefaultComponentProvider provider : providerList) {
                            if (Objects.equals(provider.getID(), ID)) {
                                fl = provider.get(rideable);
                            }
                        }
                    }
                    ComponentEntity component =
                            new ComponentEntity(RIDEABLE_COMPONENT_ENTITY_TYPE.get()
                                    , level, rideable, fl);
                    component.setID(ID);
                    component.setPos(player.getX(), player.getY(), player.getZ());
                    level.addFreshEntity(component);
                    component.startRiding(rideable, true);


                    ComponentSpawnS2CPacket packet = new ComponentSpawnS2CPacket(ID, component.getId(), rideable.getId());
                    ACHMessages.CHANNEL.send(
                            PacketDistributor.TRACKING_ENTITY_AND_SELF.with(() -> rideable),
                            packet
                    ); // 广播给所有追踪该RideableEntity的玩家

                }

            }
        });
        return true;
    }

    public static void register(SimpleChannel channel) {
        channel.messageBuilder(ComponentSpawnC2SPacket.class, ACHMessages.id(), NetworkDirection.PLAY_TO_SERVER)
                .decoder(ComponentSpawnC2SPacket::new)
                .encoder(ComponentSpawnC2SPacket::toBytes)
                .consumerMainThread(ComponentSpawnC2SPacket::handle)
                .add();
    }
}